import {useEffect, useRef, useState} from "react";
import {FormItemInstance} from "@taroify/core/form";
import {Field, Input, Picker, Popup} from "@taroify/core";
import {PickerOptionData} from "@taroify/core/picker/picker.shared";

function FormPicker({
                        rules,
                        options,
                        initVal,
                        name,
                        label,
                    }:{
    rules?: object[],
    options: PickerOptionData[],
    initVal: string,
    name: string,
    label: string
}) {
    const itemRef = useRef<FormItemInstance>()
    const [open, setOpen] = useState(false)
    const [showName, setShowName] = useState('')

    const handChange = (val: string) => {
        const str = (options.find(item => {
            return item.value === val
        })?.label || val)
        setShowName(str ? (str + '') : '')
    }
    useEffect(() => {
        handChange(initVal)
    }, [initVal, options])

    useEffect(() => {
        itemRef.current?.setValue(initVal)
    }, [initVal])

    return (
        <>
            <Field label={label} ref={itemRef} name={name} rules={rules} clickable isLink>
                <Input
                    readonly
                    placeholder="点击选择"
                    value={showName}
                    onClick={() => setOpen(true)} />
            </Field>
            <Popup open={open} rounded placement="bottom" onClose={setOpen}>
                <Picker
                    title="请选择"
                    columns={options}
                    onCancel={() => setOpen(false)}
                    onConfirm={(newValue) => {
                        handChange(newValue[0])
                        itemRef.current?.setValue(newValue[0])
                        setOpen(false)
                    }}
                ></Picker>
            </Popup>
        </>
    )
}

export default FormPicker